/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers.mobileweb;

import app.Const;
import app.events.EventBusContext;
import app.events.stat.ParkingEvent;
import app.interceptors.MobileWxMemberInterceptor;
import app.kits.ParkingNavKit;
import app.models.member.Member;
import app.models.parking.MemberParking;
import app.models.parking.Parking;
import com.github.sog.config.StringPool;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.github.sog.kit.Tuple;
import com.github.sog.libs.AppFunc;
import com.google.common.io.Files;
import com.google.common.primitives.Ints;
import com.jfinal.aop.Before;
import com.jfinal.kit.PathKit;
import org.joda.time.DateTime;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * .
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-04-26 12:32
 * @since JDK 1.6
 */
@Before(MobileWxMemberInterceptor.class)
public class NavigationController extends BasicController {

    /**
     * The index route.
     */
    public void index() {
        renderNull();
    }


    public void parking() {

        long member_id = getParaToLong(Const.MEMBER_PARAM, 0l);
        if (member_id > 0) {
            Member member = Member.dao.findById(member_id);
            setAttr(Const.MEMBER_ATTR, member);
            render("parking_new.ftl");
        } else {
            renderNull();
        }
    }

    public void current() {

        final long member_id = getParaToLong(0, 0l);
        if (member_id > 0) {
            MemberParking memberParking = MemberParking.dao.findByMember(member_id);
            renderJson(AjaxMessage.ok(memberParking));
        } else {
            renderJson(AjaxMessage.nodata());
        }
    }


    public void stop_space() {
        long member_id = getParaToLong(Const.MEMBER_PARAM, 0l);
        if (member_id > 0) {
            String target_park = getPara("traget");
            MemberParking memberParking = MemberParking.dao.findByMember(member_id);
            final boolean isNew = memberParking == null;
            if (isNew) {
                memberParking = new MemberParking();
                memberParking.set("member", member_id);
            }
            int type = getParaToInt("floor_type", 1);

            String floorName = type == 1 ? "B2层" : "同层";

            Parking target = Parking.dao.findbyLocation(target_park, type);
            if (target == null) {
                renderError("无法在" + floorName + "找到停车位置!");
                return;
            }
            memberParking.set("stop_position", target.getNumber(AppFunc.TABLE_PK_COLUMN));
            memberParking.set("stop_val", target_park);
            if (isNew) {
                memberParking.save();
            } else {
                memberParking.update();
            }
            renderSuccess();
        } else {
            renderError("请输入正确的信息");
        }
    }


    public void direct() {
        long member_id = getParaToLong(Const.MEMBER_PARAM, 0l);
        if (member_id > 0) {
            Member member = Member.dao.findById(member_id);

            String target_park = getPara("traget");
            String current_park = getPara("current");
            // default 1 ,is b2 floor .
            int type = getParaToInt("floor_type", 1);

            final boolean b2 = type == 1;
            String floorName = b2 ? "B2层" : "同层";

            Parking target = Parking.dao.findbyLocation(target_park, type);
            boolean ispeer = false;
            if (target == null) {
                setAttr(Const.MESSAGE_ATTR, "停车位置无法在" + floorName + "找到，请重新输入");
            } else {
                if (member != null) {
                    MemberParking memberParking = MemberParking.dao.findByMember(member_id);
                    final boolean isNew = memberParking == null;
                    if (isNew) {
                        memberParking = new MemberParking();
                        memberParking.set("member", member_id);
                    }
                    memberParking.set("stop_position", target.getNumber(AppFunc.TABLE_PK_COLUMN));
                    memberParking.set("stop_val", target_park);
                    if (isNew) {
                        memberParking.save();
                    } else {
                        memberParking.update();
                    }

                }
                Parking current = Parking.dao.findbyLocation(current_park, type);
                if (current == null) {
                    setAttr(Const.MESSAGE_ATTR, "当前位置信息错误，请重新输入");
                } else {
                    ispeer = target.getNumber("floor").equals(current.getNumber("floor"));
                    if (ispeer) {
                        // peer
                        String floor_mark = target.getStr("nick_name");
                        List<String> current_points = AppFunc.COMMA_SPLITTER.splitToList(current.getStr("location"));
                        List<String> target_points = AppFunc.COMMA_SPLITTER.splitToList(target.getStr("location"));
                        List<Tuple<Integer, Integer>> roads = ParkingNavKit.path(floor_mark
                                , Ints.tryParse(target_points.get(0)), Ints.tryParse(target_points.get(1))
                                , Ints.tryParse(current_points.get(0)), Ints.tryParse(current_points.get(1)));
                        if (roads == null || roads.isEmpty()) {
                            setAttr(Const.MEMBER_ATTR, "未找到导航路径！");
                        } else {
                            String dest_path = "/attachment/parking/" + type + StringPool.DASH
                                    + target_park + StringPool.DASH + current_park + ".jpg";
                            final String webRootPath = PathKit.getWebRootPath();
                            final String dest_path_curs = (webRootPath + dest_path).replace("/", File.separator);
                            final File dest_file = new File(dest_path_curs);
                            final boolean exists = dest_file.exists();
                            if (!exists) {
                                try {
                                    Files.createParentDirs(dest_file);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                ParkingNavKit.build_road(webRootPath + target.getStr("picture"), dest_path_curs, roads);
                            }

                            setAttr("parking_path", dest_path);
                        }
                        setAttr("target", target);
                        setAttr("parking", current);
                        ispeer = true;

                    } else {
                        // not peer.
                        setAttr("target", target);
                        setAttr("parking", current);
                    }

                }
            }
            EventBusContext.post(new ParkingEvent(member_id, DateTime.now().toDate(), current_park, target_park, b2));
            render(ispeer ? "nav_peer.ftl" : "nav_direct.ftl");
        } else {
            renderNull();
        }
    }

    public void clean() {

        long member_id = getParaToLong(Const.MEMBER_PARAM, 0l);
        if (member_id > 0) {
            MemberParking memberParking = MemberParking.dao.findByMember(member_id);
            if (memberParking != null) {
                memberParking.delete();
            }
            renderSuccess();
        } else {
            renderError("未知信息");
        }
    }
}